package com.chen;

import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.text.SimpleDateFormat;
import java.util.Date;

@SpringBootTest
public class TestRabbit {
    //交换机
    public static final String EXCHANGE_DIRECT = "exchange1";
    //路由键
    public static final String ROUTING_KEY = "routingKey1";


    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     *  测试延迟插件
     */

    @Test
    void testDelayPlugin() {
        // 创建消息后置处理器
        MessagePostProcessor messagePostProcessor=message -> {
            //安装插件后 x-delayed-message-exchange 才能识别x-delay 参数
            message.getMessageProperties().setHeader("x-delay",5000); //过期时间 单位毫秒
            return message;
        };
        //发送消息
        rabbitTemplate.convertAndSend("exchange.delay",
                "delay.routingkey",
               "delayPlugin message"+ new SimpleDateFormat("HH:mm:ss").format(new Date()),
                messagePostProcessor
        );
    }

    /**
     * 测试超时,进入死信队列
     */
    @Test
    public void testSendMultiMessage() {
        for (int i = 0; i < 20; i++) {
            rabbitTemplate.convertAndSend(
                    "normal.exchange",
                    "normal.routingkey",
                    "测试死信情况2：消息数量超过队列的最大容量" + i);
        }
    }

    @Test
    void testTimeOutPostProcesser() {
        MessagePostProcessor messagePostProcessor = message -> {
            message.getMessageProperties().setExpiration("6000"); //单位也是毫秒
            return message;
        };
        rabbitTemplate.convertAndSend("timeout.exchange","timeout.routingKey" ,"testTimeout",messagePostProcessor);

    }

    @Test
    void testTimeOut() {
        for (int i = 0; i < 100; i++) {
            rabbitTemplate.convertAndSend("timeout.exchange","timeout.routingKey" ,"testTimeout");
        }
    }

    @Test
    void testPrefetch() {
        for (int i = 0; i < 100; i++) {
            rabbitTemplate.convertAndSend(EXCHANGE_DIRECT,ROUTING_KEY ,"testPreCatch");
        }
    }

    @Test
    void testConfirm() {
        // 不能改交换机的名字, 因为备份交换机是和交换机绑定的
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT, ROUTING_KEY+"aa", "confirm message");
    }

    @Test
    void testSend() {
//        根据 交换机和路由键就可以定位到 队列
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT, ROUTING_KEY, "hello rabbit, I am springBoot");
    }





}
